import { z } from 'zod'
import type { ComponentSchema, ValidationResult } from '@/types'

// 定义合法的组件Schema（文章中的关键代码）
const ButtonSchema = z.object({
  component: z.literal('d-button'),
  props: z.object({
    bsStyle: z.enum(['common', 'primary', 'danger']).optional(),
    text: z.string(),
    disabled: z.boolean().optional(),
    onClick: z.string().optional()
  })
})

const TableSchema = z.object({
  component: z.literal('d-table'),
  props: z.object({
    columns: z.array(z.object({
      field: z.string(),
      header: z.string()
    })),
    data: z.array(z.record(z.any())),
    stripe: z.boolean().optional(),
    headerBg: z.string().optional()
  })
})

const CardSchema = z.object({
  component: z.literal('d-card'),
  props: z.object({
    title: z.string().optional(),
    shadow: z.boolean().optional()
  }),
  children: z.array(z.any()).optional()
})

const ComponentSchema = z.union([ButtonSchema, TableSchema, CardSchema])
const RootSchema = z.array(ComponentSchema)

// 校验函数（文章中的关键代码）
export function validateSchema(json: any): ValidationResult {
  try {
    const result = RootSchema.safeParse(json)

    if (!result.success) {
      console.error("AI 生成了非法参数,已自动回退", result.error)
      return {
        valid: false,
        error: result.error.message
      }
    }

    return {
      valid: true,
      data: result.data
    }
  } catch (error) {
    return {
      valid: false,
      error: error instanceof Error ? error.message : 'Unknown error'
    }
  }
}

// 降级处理函数
export function fallbackUI(): ComponentSchema[] {
  return [
    {
      component: 'd-card',
      props: { title: '默认视图' },
      children: [
        {
          component: 'd-button',
          props: { 
            text: '重新生成',
            bsStyle: 'primary',
            onClick: 'emit:regenerate'
          }
        }
      ]
    }
  ]
}